import { NextResponse } from "next/server";
const COS = require('cos-nodejs-sdk-v5');

const cos = new COS({
  SecretId: process.env.TENCENT_SECRET_ID,
  SecretKey: process.env.TENCENT_SECRET_KEY,
});



export async function GET(request: Request, { params }: { params: { key: string } }) {
    const { key } = params;
    console.log(key)
  
    try {
      // 生成预签名URL
      const presignedUrl = await new Promise<string>((resolve, reject) => {
        cos.getObjectUrl({
          Bucket: process.env.TENCENT_COS_BUCKET,
          Region: process.env.TENCENT_COS_REGION,
          Key: 'img/'+key,
          Method: 'GET',
          Expires: 60, // URL有效期60秒
        }, function(err: Error, data: any) {
          if (err) reject(err);
          else resolve(data.Url);
        });
      });
  
      console.log('Requested file:', key);
  console.log('Generated presigned URL:', presignedUrl);
  
      // 获取图片数据
      const response = await fetch(presignedUrl);
      if (!response.ok) throw new Error('Failed to fetch image');
      
      
      // 返回图片
      return new Response(response.body, {
        headers: {
          'Content-Type': response.headers.get('Content-Type') || 'image/*',
          'Cache-Control': 'public, max-age=60', // 缓存60秒
        },
      });
    } catch (error) {
      return new Response('Failed to fetch image', { status: 500 });
    }
  }